package com.hj.gateway.config;

import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler;
import com.alibaba.fastjson2.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author hj
 * @Date 2023/5/22
 * @Description: 限流回调处理
 */
@Component
public class SentinelFallbackHandler implements BlockRequestHandler {

    @Override
    public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
        GatewayExceptionResp resp = new GatewayExceptionResp();
        resp.setCode(429);
        resp.setMsg("请求频繁~服务限流了");
        return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                .contentType(MediaType.valueOf("application/json;charset=UTF-8"))
                .bodyValue(JSON.toJSONBytes(resp));
    }


}
